<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.phone" placeholder="手机号" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.logonstatus" placeholder="请选择号码状态" clearable style="width: 200px"
        class="filter-item">
        <el-option v-for="item in logonstatuslist" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.zid" placeholder="请选择分组" clearable style="width: 200px" class="filter-item">
        <el-option v-for="item in fzOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加号码
      </el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="alllogin">
        批量登陆
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="alltypes">
        批量检测
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-upload2"
        @click="handleUpload">
        导入数据
      </el-button>
    </div>
    <el-table :key="tableKey" ref="multipleTable" @selection-change="handleSelectionChange" v-loading="listLoading"
      :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
        :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分组" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.zname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细数据" width="100px" align="center">
        <template slot-scope="{row}">
          <el-popover trigger="hover" placement="top">
            <p>消息私钥: {{ row.IdentityPriKey }}</p>
            <p>消息公钥: {{ row.IdentityPubKey }}</p>
            <p>静态私钥: {{ row.StaticPriKey }}</p>
            <p>静态公钥: {{ row.StaticPubKey }}</p>
            <p>号码ID: {{ row.PhoneId }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">详细数据</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <!-- <el-table-column label="协议数据" width="150px" align="center">
        <template slot-scope="{row}">
          <el-popover trigger="hover" placement="top">
            <p>{{ row.jsonalls }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">协议数据</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" class-name="status-col" width="120">
        <template slot-scope="{row}">
          <el-tag :type="row.logonstatus | statusFilter">
            {{ row.logonstatus == 1 ? '待登陆' : row.logonstatus == 2 ? '登陆中' : row.logonstatus == 3 ? '登陆失败' :
        row.logonstatus == 5 ? '消息密钥异常' : '需查询登陆状态' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="登陆失败次数" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sbnum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="460" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button size="mini" v-if="row.logonstatus == 1 || row.logonstatus == 3" type="success"
            @click="logins(row, 'published')">
            登陆
          </el-button>
          <el-button size="mini" v-if="row.logonstatus == 4" type="success" @click="getLoginTypes(row)">
            检测
          </el-button>
          <el-button size="mini" type="danger" v-if="row.logonstatus != 2" @click="handleDelete(row, $index)">
            删除
          </el-button>
          <el-button size="mini" type="primary" v-if="row.logonstatus != 1" @click="getloglist(row, $index)">
            日志
          </el-button>
          <el-button size="mini" type="warning" v-if="row.logonstatus != 2" plain @click="handleUpdate(row, $index)">
            编辑
          </el-button>
          <!-- <el-button size="mini" type="primary" plain @click="cp(row, $index)">
            复制
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column label="手机号" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column label="json数据" width="250px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.jsonall }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="150px" align="center">
          <template slot-scope="{row}">
            <el-tag>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }} </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="impoleVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="分组" prop="username">
          <el-select v-model="temp.zid" placeholder="请选择分组">
            <el-option v-for="item in fzOptions" :key="item.id" :label="item.name" :value="item.id"
              value-key="id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导入账号">
          <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
        </el-form-item>
        <el-form-item label="账号" prop="phonelist">
          <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 24 }" maxlength="40" v-model="temp.phonelist" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          导入数据
        </el-button>
      </div>
    </el-dialog>
    <!-- 修改号码信息 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="editVisible">
      <el-form ref="dataForm" :rules="rules" :model="editinfo" label-position="left" label-width="70px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="账号" prop="phone">
          <el-input v-model="editinfo.phone" />
        </el-form-item>
        <el-form-item label="分组" prop="username">
          <el-select v-model="editinfo.zid" placeholder="请选择分组">
            <el-option v-for="item in fzOptions" :key="item.id" :label="item.name" :value="item.id"
              value-key="id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息私钥" prop="IdentityPriKey">
          <el-input v-model="editinfo.IdentityPriKey" />
        </el-form-item>
        <el-form-item label="消息公钥" prop="IdentityPubKey">
          <el-input v-model="editinfo.IdentityPubKey" />
        </el-form-item>
        <el-form-item label="静态私钥" prop="StaticPriKey">
          <el-input v-model="editinfo.StaticPriKey" />
        </el-form-item>
        <el-form-item label="静态公钥" prop="StaticPubKey">
          <el-input v-model="editinfo.StaticPubKey" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          修改
        </el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import { fetchList, fetchPv, getDel, getLogin, getImplode, getLoginType, getFzList, rwlog, updateArticle }
  from '@/api/smsck'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
const statusOptions = [
  { key: 1, display_name: '授权' },
  { key: 2, display_name: '未授权' },
  { key: 3, display_name: '封禁' },
  { key: 4, display_name: '异常' }
]
export default {
  name: 'ComplexTable',
  components: { Pagination, UploadExcelComponent },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        phone: '',
        logonstatus: '',
        zid: ''
      },
      multipleSelection: [],
      statusOptions,
      showReviewer: false,
      temp: {
        id: undefined,
        listall: [],
        phonelist: '',
        zid: '',
      },
      editinfo: {
        id: undefined,
        phone: '',
        zid: '',
        IdentityPriKey: '',
        StaticPriKey: '',
        StaticPubKey: '',
        IdentityPubKey: '',
        status: '',
      },
      fzOptions: [],
      logonstatuslist: [{ label: '请选择', key: '' }, { label: '待核实', key: '1' }, { label: '登陆中', key: '2' }, { label: '登陆失败', key: '3' }, { label: '密钥失败', key: '5' }],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create',
        getlist: 'GET',
        loglist: '登陆日志',
        impolephone: 'Impole'
      },
      impoleVisible: false,
      dialogPvVisible: false,
      editVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getFzListall()
  },
  methods: {

    getFzListall() {
      getFzList().then(response => {
        console.log(response.data)
        this.fzOptions = response.data.list
      })
    },
    alllogin() {
      let list = this.multipleSelection
      let arr = []
      list.forEach(function (item, index) {
        console.log(item); //输出数组的每一个元素
        if (item.logonstatus != 5) {
          arr.push(item.phone)
        }
      });
      if (arr.length > 0) {
        //进行登陆操作
        let temp = {
          phone: arr.join(",")
        }
        this.listLoading = true
        getLogin(temp).then(response => {
          this.$message({
            message: '操作Success',
            type: 'success'
          })
          this.getList();
          this.listLoading = false
        })
      }
    },
    alltypes() {
      let list = this.multipleSelection
      let arr = []
      list.forEach(function (item, index) {
        console.log(item); //输出数组的每一个元素
        //if (item.logonstatus != 2) {
        arr.push(item.phone)
        //}
      });
      if (arr.length > 0) {
        //进行登陆操作
        let temp = {
          phone: arr.join(",")
        }
        this.listLoading = true
        getLoginType(temp).then(response => {
          this.$message({
            message: '操作Success',
            type: 'success'
          })
          this.getList();
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      }
    },
    getLoginTypes(row) {
      this.listLoading = true
      getLoginType({ phone: row.phone }).then(response => {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        this.getList();
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },




    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log('导入数据', this.multipleSelection)
    },
    cp(row, index) {
      let inputDom = document.createElement('textarea') // js创建一个文本框
      document.body.appendChild(inputDom) //将文本框暂时创建到实例里面
      inputDom.value = row.jsonalls //将需要复制的内容赋值到创建的文本框中
      inputDom.select() //选中文本框中的内容
      inputDom.focus()
      document.execCommand('copy') //执行复制操作
      document.body.removeChild(inputDom) //最后移出
      this.$notify({
        title: 'Success',
        message: '复制完成',
        type: 'success',
        duration: 2000
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        console.log(response.data)
        this.list = response.data.list
        this.total = response.data.count
        // Just to simulate the time of the request
        this.listLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    logins(row, status) {
      //进行登陆操作
      let temp = {
        phone: row.phone
      }
      this.listLoading = true
      getLogin(temp).then(response => {
        if (response.code == 200) {
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '失败',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
        this.getList()
        this.listLoading = false
      })
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },

    getloglist(row, index) {
      //查询数据
      rwlog({ phone: row.phone }).then(response => {
        this.pvData = response.data
      })
      this.dialogStatus = 'loglist'
      this.dialogFormVisible = true
    },
    handleUpload() {
      this.dialogStatus = 'impolephone'
      this.impoleVisible = true
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      console.log(results)
      console.log(header)
      this.temp.listall = results
      let listall = results
      let arr = []
      listall.forEach(function (item, index) {
        arr.push(item.账号)
      });
      let arrs = arr.join(",");
      console.log(arrs);
      //输出数组的每一个元素
      this.temp.phonelist = arrs

    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          getImplode(this.temp).then(response => {
            this.$notify({
              title: 'Success',
              message: '导入完成',
              type: 'success',
              duration: 2000
            })
            this.impoleVisible = false
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    editinfoTemp(row) {
      this.editinfo.id = row.id
      this.editinfo.phone = row.phone
      this.editinfo.zid = row.zid
      this.editinfo.IdentityPriKey = row.IdentityPriKey
      this.editinfo.IdentityPubKey = row.IdentityPubKey
      this.editinfo.StaticPriKey = row.StaticPriKey
      this.editinfo.StaticPubKey = row.StaticPubKey
      this.editinfo.status = row.status
    },
    handleUpdate(row) {
      this.editinfoTemp(row)
      // this.editinfo = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.editVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.editinfo)
          updateArticle(tempData).then(() => {
            this.editVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      let temp = {
        phone: row.phone
      }
      getDel(temp).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Created Successfully',
          type: 'success',
          duration: 2000
        })
      })
      this.list.splice(index, 1)
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
